#import <QuartzCore/QuartzCore.h>
#import "JokeViewController.h"
#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "PostViewController.h"
#import "JokeManager.h"
#import "UserManager.h"
#import "DBManager.h"
#import "NetWorkManager.h"
#import "MenuViewController.h"
#import "ColdAppDelegate.h"
#import "RegexKitLite.h"
#import "DataCacheManager.h"

@implementation JokeViewController
@synthesize homeWindow;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //
    }
    return self;
}

- (void)dealloc {
    PP_RELEASE(jokePageViewContainer);
    PP_RELEASE(jokeColumnViewContainer);
    PP_RELEASE(jokePageView);
    PP_RELEASE(jokeColumnView);
    PP_RELEASE(shareViewController);
    PP_RELEASE(jokeManagerAll);
    PP_RELEASE(jokeManagerHot);
    PP_RELEASE(jokeManagerShit);
    PP_RELEASE(guideView1);
    PP_RELEASE(guideView1Btn);
    PP_RELEASE(guideView2);
    PP_RELEASE(guideView2Btn);
    PP_RELEASE(homeWindow);
    PP_RELEASE(hudLoading);
    PP_RELEASE(collectBtn);
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.viewDeckController.centerhiddenInteractivity = IIViewDeckCenterHiddenNotUserInteractiveWithTapToClose;
    self.viewDeckController.delegate = self;
    self.navigationController.navigationBar.backgroundColor =[UIColor clearColor];
    baseTitle.text = @"爱讲冷笑话";

    NSArray *pageNibList = [[NSBundle mainBundle] loadNibNamed:@"JokePageView" owner:self options:nil];
    jokePageView = [[pageNibList objectAtIndex:0] retain];
    [jokePageViewContainer addSubview:jokePageView];
    
    NSArray *columnNibList = [[NSBundle mainBundle] loadNibNamed:@"JokeColumnView" owner:self options:nil];
    jokeColumnView = [[columnNibList objectAtIndex:0] retain];
    [jokeColumnViewContainer addSubview:jokeColumnView];
    
    //菜单按钮
    UIButton* menuBtn= [[[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 44.0, 44.0)] autorelease];
    [menuBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_menu_1.png"] forState:UIControlStateNormal];
    [menuBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_menu_2.png"] forState:UIControlStateHighlighted];
    [menuBtn addTarget:self action:@selector(showMenu) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *menuBarBtn = [[[UIBarButtonItem alloc] initWithCustomView:menuBtn] autorelease];
    [self.navigationItem setLeftBarButtonItem:menuBarBtn];
    
    //菜单按钮
    collectBtn= [[[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 44.0, 44.0)] autorelease];
    [collectBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_collect_1.png"] forState:UIControlStateNormal];
    [collectBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_collect_2.png"] forState:UIControlStateHighlighted];
    [collectBtn addTarget:self action:@selector(showList) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *collectBarBtn = [[[UIBarButtonItem alloc] initWithCustomView:collectBtn] autorelease];
    [self.navigationItem setRightBarButtonItem:collectBarBtn];
    
    hudLoading = [[MBProgressHUD showHUDAddedTo:self.view animated:YES] retain];
    hudLoading.labelText = @"正在加载...";
    hudLoading.opacity = PP_mbprogressHudOpacity;
    
    jokeManagerAll = [[JokeManager alloc] initWithSort:0 :@"all" :@"new" :self];
    jokeManagerHot = [[JokeManager alloc] initWithSort:1 :@"hot" :@"popular" :self];
    jokeManagerShit = [[JokeManager alloc] initWithSort:2 :@"shit" :@"shit" :self];
    [DataCacheManager sharedInstance].jokeManagerAll = jokeManagerAll;
    [DataCacheManager sharedInstance].jokeManagerHot = jokeManagerHot;
    [DataCacheManager sharedInstance].jokeManagerShit = jokeManagerShit;

    
    [[NSNotificationCenter defaultCenter] addObserver: self
                                             selector: @selector(login)
                                                 name: @"login"
                                               object: nil];
    
    [[NSNotificationCenter defaultCenter] addObserver: self
                                             selector: @selector(logout)
                                                 name: @"logout"
                                               object: nil];
    
    [jokeColumnView start:self :jokeManagerAll :jokeManagerHot :jokeManagerShit];
    [jokePageView start:self :jokeColumnView.sortPlaying.jokeManager];
    
    if( jokeManagerAll.listShow.count == 0 ){
        hudLoading.hidden = NO;
    }else{
        hudLoading.hidden = YES;
    }
    
    //初始化评论框
    [self baseInitComment:jokePageView btnName:@"评论"];
}

- (void)viewDidUnload {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"login" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"logout" object:nil];
    
    PP_RELEASE(jokePageViewContainer);
    PP_RELEASE(jokeColumnViewContainer);
    PP_RELEASE(jokePageView);
    PP_RELEASE(jokeColumnView);
    PP_RELEASE(shareViewController);
    PP_RELEASE(jokeManagerAll);
    PP_RELEASE(jokeManagerHot);
    PP_RELEASE(jokeManagerShit);
    PP_RELEASE(guideView1);
    PP_RELEASE(guideView1Btn);
    PP_RELEASE(guideView2);
    PP_RELEASE(guideView2Btn);
    PP_RELEASE(homeWindow);
    PP_RELEASE(hudLoading);
    PP_RELEASE(collectBtn);
    
    [super viewDidUnload];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];
    [ColdAppDelegate sharedAppDelegate].mainController.panningMode = IIViewDeckNoPanning;
    [self autologin];
    //    [self funciontGuidePage];
    [self funciontGuidePage];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:YES];
    [ColdAppDelegate sharedAppDelegate].mainController.panningMode = IIViewDeckFullViewPanning;
}

- (void)funciontGuidePage {
    NSString *curVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey: (NSString *)kCFBundleVersionKey];
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    NSString *view1 = [defaults stringForKey:@"guide1"];
    
    if( ![view1 isEqualToString:curVersion] ){
        [defaults setObject:curVersion forKey:@"guide1"];
        //创建图片
        guideView1 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.homeWindow.frame.size.width, self.homeWindow.frame.size.height)];
        guideView1.backgroundColor = [UIColor clearColor];
        guideView1.contentMode = UIViewContentModeScaleAspectFit;
        guideView1.image = [UIImage imageNamed:@"view_left.png"];
        
        //创建按钮
        guideView1Btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, self.homeWindow.frame.size.width, self.homeWindow.frame.size.height)];
        guideView1Btn.backgroundColor = [UIColor blackColor];
        guideView1Btn.alpha = 0.7;
        [guideView1Btn addTarget:self action:@selector(hideGuideView1) forControlEvents:UIControlEventTouchUpInside];
        
        [self.homeWindow addSubview:guideView1Btn];
        [self.homeWindow addSubview:guideView1];
    }
}

- (void)hideGuideView1 {
    if (guideView1.hidden == NO || guideView1Btn.hidden == NO) {
        guideView1.hidden = YES;
        guideView1Btn.hidden = YES;
    }
    
    NSString *curVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey: (NSString *)kCFBundleVersionKey];
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    NSString *view2 = [defaults stringForKey:@"guide2"];

    if (![view2 isEqualToString:curVersion]) {
        [defaults setObject:curVersion forKey:@"guide2"];
        //创建图片
        guideView2 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320 , 168)];
        guideView2.backgroundColor = [UIColor clearColor];
        guideView2.contentMode = UIViewContentModeScaleAspectFit;
        guideView2.image = [UIImage imageNamed:@"view_zoomInAndPress.png"];
        //创建按钮
        guideView2Btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, self.homeWindow.frame.size.width, self.homeWindow.frame.size.height)];
        guideView2Btn.backgroundColor = [UIColor blackColor];
        guideView2Btn.alpha = 0.7;
        [guideView2Btn addTarget:self action:@selector(hideGuideView2) forControlEvents:UIControlEventTouchUpInside];
        
        [self.homeWindow addSubview:guideView2Btn];
        [self.homeWindow addSubview:guideView2];
    }
}
- (void)hideGuideView2 {
    if (guideView2.hidden == NO || guideView2Btn.hidden == NO) {
        guideView2.hidden = YES;
        guideView2Btn.hidden = YES;
    }
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark -------业务方法-------

- (void)autologin {
    UserManager *userManager = [UserManager sharedInstance];
    Log(@"isLogin: %@",userManager.isLogin?@"YES":@"NO");
    if (userManager.isLogin ) {
        [jokePageView setUserState:jokePageView.userStateLogin];
    }else{
        [jokePageView setUserState:jokePageView.userStateLogout];
        if( userManager.email != nil && userManager.password != nil ){
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [userManager loginWithRecord:self];
            });
        } else {
            Log(@"autologin not needed");
        }
    }
}

- (void)login {
    [jokePageView setUserState:jokePageView.userStateLogin];
}

- (void)logout {
    [jokePageView setUserState:jokePageView.userStateLogout];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [jokeManagerAll removeLikeState];
        [jokeManagerHot removeLikeState];
        [jokeManagerShit removeLikeState];
    });
}

- (void)showMenu {
    [self.viewDeckController toggleLeftView];
}

- (void)showList {
    [self baseHideComment];
    [self JPVshowList];
}

#pragma mark –
#pragma mark ------JokeManagerDelegate------

- (void)JMloadNew:(JokeManager *)pJokeManager :(int)newCount {
    dispatch_async(dispatch_get_main_queue(), ^{
        hudLoading.hidden = YES;
    });
    [jokeColumnView doneNew:pJokeManager :newCount];
    [jokePageView doneNew:pJokeManager :newCount];
}
-(void)JMloadNext:(JokeManager *)pJokeManager :(int)nextCount {
    dispatch_async(dispatch_get_main_queue(), ^{
        hudLoading.hidden = YES;
    });
    [jokeColumnView doneNext:pJokeManager :nextCount];
    [jokePageView doneNext:pJokeManager :nextCount];
}
-(void)JMloadNewAndNext:(JokeManager *)pJokeManager :(int)newCount :(int)nextCount {
    dispatch_async(dispatch_get_main_queue(), ^{
        hudLoading.hidden = YES;
    });
    [jokeColumnView doneNewAndNext:pJokeManager :newCount :nextCount];
    [jokePageView doneNewAndNext:pJokeManager :newCount :nextCount];
}

#pragma mark -
#pragma mark -------JokePageViewDelegate 协议方法-------

- (void)JPVselect:(JokeManager *)pJokeManager :(NSIndexPath *)pJokeIndexPath {
    Log(@"JPV select : %d",pJokeIndexPath.row);
    if(pJokeIndexPath != nil){
        [jokeColumnView reload:pJokeManager :pJokeIndexPath];
    }
}
- (void)JPVshowList {
    collectBtn.enabled = NO;
    [jokePageView zoomIn];
    [jokeColumnView zoomIn];
}
- (void)JPVshare {
    [shareViewController release];
    shareViewController = [[ShareViewController alloc] initWithNibName:@"ShareViewController" bundle:nil];
    shareViewController.owner = self;
    [self presentPopupViewController:shareViewController animationType:MJPopupViewAnimationFade];
}
- (void)JPVlogin {
    [self baseShowLoginSheet];
}

#pragma mark -
#pragma mark -------JokeColumnViewDelegate 协议方法-------

- (void)JCVselect:(JokeManager *)pJokeManager :(NSIndexPath *)pJokeIndexPath {
    Log(@"JCV select : %d",pJokeIndexPath.row);
    collectBtn.enabled = YES;
    if(pJokeIndexPath != nil){
        [jokePageView reload:pJokeManager :pJokeIndexPath];
    }
    [jokeColumnView zoomOut];
    [jokePageView zoomOut];
}

- (void)JCVgetNewAndNext{
    [jokeColumnView.sortDislaying.jokeManager getNewAndNextAsync:(![[NetWorkManager sharedInstance] hasWifiNetwork])];
}
- (void)JCVgetNew {
    [jokeColumnView.sortDislaying.jokeManager getNewAsync:(![[NetWorkManager sharedInstance] hasWifiNetwork])];
}
- (void)JCVgetNext {
    [jokeColumnView.sortDislaying.jokeManager getNextAsync:(![[NetWorkManager sharedInstance] hasWifiNetwork])];
}



#pragma mark - MWPhotoBrowserDelegate

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return jokePageView.cellPlaying.scanPhotos.count;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < jokePageView.cellPlaying.scanPhotos.count){
        return [jokePageView.cellPlaying.scanPhotos objectAtIndex:index];
    }
    return nil;
}

#pragma mark -
#pragma mark -------JokeColumnCellDelegate 协议方法-------
- (void)JPCscanPhotos{
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = YES;
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browser];
    nc.modalTransitionStyle = UIModalPresentationFullScreen ;
    [self presentModalViewController:nc animated:YES];
    [nc release];
}

- (void)JPCdown {
    [jokePageView hideBar];
}

- (void)JPCup {
    [jokePageView showBar];
}

- (void)JPClogin {
    [self baseShowLoginSheet];
}

#pragma mark -
#pragma mark -------ShareViewDelegate 协议方法-------

- (void)SVDcancel {
    [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationFade];
}

- (void)SVDweixin {
    [[ShareManager sharedInstance] weixinShare:self];
}

- (void)SVDweixinFriends {
    [[ShareManager sharedInstance] weixinFriends:self];
}

- (void)SVDsinaWeibo {
    [[ShareManager sharedInstance] sinaWeibo:self];
}

- (void)SVDtencentWeibo {
    [[ShareManager sharedInstance] tencentWeibo:self];
}

- (void)SVDdouban {
    [[ShareManager sharedInstance] douban:self];
}

- (void)SVDqzone {
    [[ShareManager sharedInstance] qzone:self];
}

- (void)SVDrenren {
    [[ShareManager sharedInstance] renren:self];
}

- (void)SVDsmsMessage {
    [[ShareManager sharedInstance] smsMessage:self];
}

- (void)SVDcopy {
    JokeModel *tJoke = jokePageView.cellPlaying.jokePlaying;
    if( tJoke.jokeImgUrl.length == 0 ){
        [[ShareManager sharedInstance] copy:tJoke.jokeText];
    } else {
        [[ShareManager sharedInstance] copy:[NSString stringWithFormat:@"%@ [图片]",tJoke.jokeText]];
    }
    [self baseShowInfoHud:NSLocalizedString(@"已复制本篇至剪贴板", @"") andIsTop:NO];
}

#pragma mark -
#pragma mark -------ShareDataDelegate协议方法-------

- (ShareModel*)SMDdata {
    ShareModel *data = [[ShareModel alloc] init];
    JokeModel *tJoke = jokePageView.cellPlaying.jokePlaying;
    
    if ([tJoke.jokeText length] == 0) {
        data.title = @"我们爱讲冷笑话";
    }
    data.title = [NSString stringWithFormat:@"%@...",[tJoke.jokeText substringToIndex:8]] ;
    data.text = tJoke.jokeText;
    data.url = JOKE_SHARE_URL(tJoke.jokeId);
    data.image = nil;
    data.thumbImage = [UIImage imageNamed:@"icon_about.png"];
    if ([tJoke.jokeText length] > 50) {
        data.weiboText = [NSString stringWithFormat:@"%@ ...详情点击:%@",[tJoke.jokeText substringToIndex:50],JOKE_SHARE_URL(tJoke.jokeId)];
    }else{
        data.weiboText = [NSString stringWithFormat:@"%@ ...详情点击:%@",tJoke.jokeText,JOKE_SHARE_URL(tJoke.jokeId)];
    }
    return data;
}

- (void)viewDeckController:(IIViewDeckController*)viewDeckController didChangeOffset:(CGFloat)offset orientation:(IIViewDeckOffsetOrientation)orientation panning:(BOOL)panning {
    [self baseHideComment];
}

@end
